package br.com.passeionaweb.appengine.tabelafipe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.passeionaweb.appengine.tabelafipe.data.DataProvider;
import br.com.passeionaweb.appengine.tabelafipe.data.Make;
import br.com.passeionaweb.appengine.tabelafipe.data.Model;
import br.com.passeionaweb.appengine.tabelafipe.data.PMF;
import br.com.passeionaweb.appengine.tabelafipe.data.Version;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class UpdateVersionsServlet extends HttpServlet {

	private static final PersistenceManager pm = PMF.get().getPersistenceManager();
	private static final Logger LOG = Logger.getLogger(UpdateVersionsServlet.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
			IOException {
		long start = Calendar.getInstance().getTimeInMillis();
		boolean result = updateVersions();
		long end = Calendar.getInstance().getTimeInMillis();
		resp.getWriter().write("{result:"+result+",time:"+((end - start) / 1000)+"}");

	}

	private boolean updateVersions() {
		try {
			JSONArray jsonVersions = new JSONArray(DataProvider.getVersionsJSON());
			List<Version> versions = new ArrayList<Version>();
			Model model = null;
			for (int i = 0; i < jsonVersions.length(); ++i) {
				JSONObject jsonversion = jsonVersions.getJSONObject(i);
				String makeName = jsonversion.getString(Make.KEY_MAKE);
				String modelName = jsonversion.getString(Model.KEY_MODEL);
				String versionName = jsonversion.getString(Version.KEY_VERSION);

				if (model == null || model.getModel()!= modelName) {
					if (Model.exists(modelName)) {
						model = Model.getModel(modelName);
					} else {
						model = new Model(modelName, Make.getMake(makeName).getId());
						pm.makePersistent(model);
						model = Model.getModel(modelName);
					}
				}

				if (!Version.exists(versionName)) {
					versions.add(new Version(versionName, model.getId()));
				}
				logPercentage(i, jsonVersions.length());
			}

			if (versions.size() != 0) {
				pm.makePersistentAll(versions);
			}
			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			LOG.log(Level.SEVERE, "error updating versions", e);
			return false;
		}
	}

	private void logPercentage(int done, int size) {
		float percentage = Float.valueOf(done) / Float.valueOf(size) * 100;
		LOG.info("Updating VERSIONS: " + percentage + "%");
	}
}
